package com.example.ota_ble

import android.animation.Animator
import android.animation.AnimatorListenerAdapter
import android.animation.ObjectAnimator
import android.annotation.SuppressLint
import android.app.AlertDialog
import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothDevice
import android.bluetooth.BluetoothGatt
import android.bluetooth.le.BluetoothLeScanner
import android.bluetooth.le.ScanCallback
import android.bluetooth.le.ScanResult
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.content.pm.PackageManager
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.text.Editable
import android.util.Log
import android.view.View
import android.widget.Button
import android.widget.EditText
import android.widget.ImageView
import android.widget.SeekBar
import android.widget.TextView
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.annotation.RequiresApi
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import androidx.core.widget.addTextChangedListener
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.findNavController
import androidx.navigation.ui.navigateUp
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.example.ota_ble.ble.adv.advRspRecall
import com.example.ota_ble.ble.component.scanListAdapter
import com.example.ota_ble.ble.connect.buletoothGattManage
import com.example.ota_ble.ble.data.dataBlueScanItem
import com.example.ota_ble.permiss.permissionRsq
import com.example.ota_ble.ui.theme.OTA_BLETheme
@SuppressLint("RestrictedApi","MissingPermission")
class MainActivity : ComponentActivity() {

    val TAG = "rocjan.MainActivity"

    /**
     *  sys
     * */

    lateinit var next_intent: Intent
    /*
    *   1、蓝牙
    * */
    lateinit var bluetoothAdapter: BluetoothAdapter   //sys
    lateinit var bluetoothAdvManage: advManage   //sys


    lateinit var  blueScanner: BluetoothLeScanner

    lateinit var blueScannerCallbk : ScanCallback
    lateinit var bluetoothscanListAdapter : scanListAdapter //user
    var that = this
    // debug
    lateinit var main_seekbar_rssi: TextView
    var filters_rssi: Short = -60
    var filters_name: String = "rocjan"
    /**
     *
     * */
    lateinit var   scanImageView: ImageView
    private var deviceList = mutableListOf<dataBlueScanItem>()

    @RequiresApi(Build.VERSION_CODES.O)
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        // 1、检查
        permissionRsq.check_need_premissionList(this)
        // 2、初始化
        /*
        *   1、蓝牙列表 adapt初始化
        * */
        // 在 Activity 中使用 ViewModel

        var recyclerView = findViewById<RecyclerView>(R.id.ble_scan_recycler_view)
        recyclerView.layoutManager = LinearLayoutManager(this)
        bluetoothscanListAdapter = scanListAdapter(deviceList)
        bluetoothscanListAdapter.register_ListItemClickLister(object :scanListAdapter.Companion.OnScanListItemClickLister
        {
            override fun on_click_item(bluetoothDev: BluetoothDevice) {
                Log.i(TAG,"${bluetoothDev.address } --")
                if(bluetoothAdapter.isDiscovering) bluetoothAdapter.cancelDiscovery()
                stop_scan_ble_dev()

                jump_next_activity(bluetoothDev)
            }

        }
        )
        recyclerView.adapter = bluetoothscanListAdapter
        /*
        *   2、蓝牙初始化
        * */
        // 1、检测蓝牙是否正常，打开蓝牙
        this.bluetoothAdapter = BluetoothAdapter.getDefaultAdapter()
        if(this.bluetoothAdapter==null){

        }else{
            if(!bluetoothAdapter.isEnabled())
            {
                bluetoothAdapter.enable()
            }
        }

        // 蓝牙广播注册
        this.bluetoothAdvManage = advManage()
        registerReceiver(bluetoothAdvManage.get_BdReceiver() ,bluetoothAdvManage.get_BdReceivIntentFilter())
        // 蓝牙连接注册

        /*
        *   3、组件初始化
        * */
        var main_ble_name_filter  = findViewById<EditText>(R.id.ble_name_filter)
        main_ble_name_filter.setText("rocjan")
        main_ble_name_filter.addTextChangedListener(object :  android.text.TextWatcher {
            override fun beforeTextChanged(charSequence: CharSequence?, start: Int, before: Int, after: Int) {
                // 文本变化之前调用
            }

            override fun onTextChanged(charSequence: CharSequence?, start: Int, before: Int, after: Int) {
                // 文本正在变化时调用
            }

            override fun afterTextChanged(editable: Editable?) {
                // 文本变化之后调用

                this@MainActivity.filters_name = editable.toString()

                Log.i(TAG,this@MainActivity.filters_name  )
                // 例如：过滤或者进行一些处理
            }
        })

        var main_btn_name  = findViewById<Button>(R.id.str_main_btn_name)
        main_btn_name.setOnClickListener {
            if(!bluetoothAdapter.isDiscovering) bluetoothAdapter.startDiscovery()
            start_scan_ble_dev()
        }
        main_seekbar_rssi= findViewById<TextView>(R.id.main_seekbar_rssi)
        main_seekbar_rssi.text = filters_rssi.toString()
        var main_seekbar_id = findViewById<SeekBar>(R.id.main_seekbar_id)
        main_seekbar_id.max = -10
        main_seekbar_id.min = -100
        main_seekbar_id.progress = filters_rssi.toInt()
        main_seekbar_id.setOnSeekBarChangeListener(
            object : SeekBar.OnSeekBarChangeListener{
                override fun onProgressChanged(
                    seekBar: SeekBar?,
                    progress: Int,
                    fromUser: Boolean
                ) {
                    main_seekbar_rssi.text = progress.toString()
                }

                override fun onStartTrackingTouch(seekBar: SeekBar?) {

                }

                override fun onStopTrackingTouch(seekBar: SeekBar?) {

                }

            }
        )

        scanImageView = findViewById<ImageView>(R.id.scanImageView)


        this.blueScanner  = bluetoothAdapter.bluetoothLeScanner
        blueScannerCallbk = object : ScanCallback()
        {
            override fun onScanResult(callbackType: Int, result: ScanResult?) {


                var device  = result?.device
                var rssi = result!!.rssi.toShort()
                var ret = filterDevice_isVaild(device as BluetoothDevice,rssi)
                if(ret!=false)
                {
                    // 获取广播包数据
                    var scanRecord = result.getScanRecord()!!.getBytes();
                    // 你可以在这里解析扫描包数据，打印出来或做进一步处理
                    var idx = scanRecord.indexOf(0x1e)

                    var version:ByteArray = ByteArray(2)

                    version[0]  = if(idx!=-1) scanRecord[idx+4] else -1
                    version[1]  = if(idx!=-1) scanRecord[idx+5] else -1
                    this@MainActivity.deviceList.add(dataBlueScanItem(device,rssi.toString(),version))
                    this@MainActivity.bluetoothscanListAdapter.notifyDataSetChanged()

                    Log.d(TAG, "Scan Result: " + scanRecord.joinToString(" "){it.toUByte().toString(16).padStart(2,'0')});
                    Log.e(TAG,"scan result resp name: ${device?.name}")
                }



            }

            override fun onScanFailed(errorCode: Int) {

            }
        }


    }

    fun start_scan_ble_dev()
    {
        this.blueScanner.startScan(this.blueScannerCallbk)
        var handle = Handler()
        var stop_runable = object  : Runnable  {
            override fun run() {
                stop_scan_ble_dev()
            }
        }
        scanImageView.visibility = View.VISIBLE
        Glide.with(this@MainActivity)
            .asGif()
            .load(R.drawable.load) // 第一个 GIF 图像
            .into(scanImageView)
        this@MainActivity.deviceList.clear()
        this@MainActivity.bluetoothscanListAdapter.notifyDataSetChanged()


        handle.postDelayed(stop_runable,10 * 1000)

    }
    fun stop_scan_ble_dev()
    {

        this.blueScanner.stopScan(this.blueScannerCallbk)
        scanImageView.visibility = View.GONE
        Glide.with(this@MainActivity).clear(scanImageView)  // 停止并清除 ImageView 中的图片
    }









    /*************************************与主逻辑无关****************************************/
    //  1、权限回调
    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        var need_permission_num = 0

        if(requestCode == 1000)
        {
            for( i in grantResults.indices)
            {
                if(grantResults[i]!=PackageManager.PERMISSION_GRANTED)
                {
                    need_permission_num ++
                    Log.i(TAG,"wait_rsq:${permissions[i]}")
                }
            }
            if(need_permission_num>0)
            {
                Log.i(TAG,"需要打开部分授权，应用才可以进行")
            }

        }

    }
    //  2、扫描设备过滤函数
    fun filterDevice_isVaild(bluetoothDevice: BluetoothDevice, rssi: Short?)  : Boolean
    {

        var name = bluetoothDevice.name
        if(name == null || rssi == null || (rssi as Short) < main_seekbar_rssi.text.toString().toShort())
        {
            return false
        }

        Log.i(TAG, "${if(filters_name.isEmpty() == false) "false" else "true"}")

        if(filters_name.isEmpty()==false&&(name.indexOf(filters_name,0)==-1)) return false

        this.deviceList.forEach {
            if((it.dev.address==bluetoothDevice.address)  ) return false
        }

        return true
    }


    /**
     *          广播的管理者,事件回调
     * */
    inner  class advManage {
        lateinit var BdReceiver:advRspRecall
        lateinit var BdReceivIntentFilter:IntentFilter
        init{

            this.init_BDReceiver()
            this.init_BdReceivIntentFilter()
        }
        /*对外接口，获取广播和事件屏蔽*/
        fun get_BdReceiver():advRspRecall = this@advManage.BdReceiver
        fun get_BdReceivIntentFilter():IntentFilter = this@advManage.BdReceivIntentFilter

        private fun init_BDReceiver()
        {
            this@advManage.BdReceiver = advRspRecall()
            this@advManage.BdReceiver.registerDeviceSearchListener(
                object : advRspRecall.Companion.OnDeviceSearchListener{
                    override fun onDiscoveryStart_Recall() {

                    }

                    override fun onDiscoveryStop_Recall() {


                    }

                    override fun onDiscoveryFound_Recall(
                        bluetoothDevice: BluetoothDevice,
                        rssi: Short?
                    ) {
//                        if(this@MainActivity.filterDevice_isVaild(bluetoothDevice,rssi)==true)
//                        {
////                            this@MainActivity.deviceList.add(dataBlueScanItem(bluetoothDevice,rssi.toString()))
////                            this@MainActivity.bluetoothscanListAdapter.notifyDataSetChanged()
//                        }

                    }

                    override fun onDevice_pairingRequest_Recall() {

                    }

                    override fun onDevice_pairingSuccess_Recall(bluetoothDevice: BluetoothDevice) {
                        //jump_next_activity(bluetoothDevice)


                    }

                    override fun onDevice_pairingFail_Recall(bluetoothDevice: BluetoothDevice) {
                        val builder = AlertDialog.Builder(this@MainActivity)
                        builder.setTitle("提示")
                        builder.setMessage("请求配对失败！！！确定将关闭程序")
                        builder.setPositiveButton("确定") { dialog, which ->
                            // 点击“确定”按钮后的操作
                            System.exit(0)
                        }
                        builder.setNegativeButton("取消") { dialog, which ->
                            // 点击“取消”按钮后的操作

                        }

                        val dialog = builder.create()
                        dialog.show()
                    }

                }
            )

        }
        private fun init_BdReceivIntentFilter()
        {
            this@advManage.BdReceivIntentFilter = IntentFilter()
            this@advManage.BdReceivIntentFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED) //开始扫描
            this@advManage.BdReceivIntentFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED)//扫描结束
            this@advManage.BdReceivIntentFilter.addAction(BluetoothDevice.ACTION_FOUND)//搜索到设备
            this@advManage.BdReceivIntentFilter.addAction(BluetoothDevice.ACTION_PAIRING_REQUEST)//搜索到设备
            this@advManage.BdReceivIntentFilter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED)//搜索到设备


        }
    }

    fun jump_next_activity(bluetoothDevice: BluetoothDevice)
    {
        next_intent = Intent(this@MainActivity, otaactivity::class.java)
        next_intent.putExtra("BLE_ADDR",bluetoothDevice.address)
        startActivity(next_intent)
    }
}

